<?php

namespace app\api\controller;

use org\Jdk_inc;
use think\Controller;
use think\Db;


error_reporting(0);
header("Access-Control-Allow-Origin:*");
class Share extends Controller
{

    /**
     * @user Maxzen
     * @note 微信token验证
     */
    public function index()
    {
        $param = input("param.");
        $timestamp = $_GET['timestamp'];
        $nonce = $_GET['nonce'];
        $token = 'chaoyujiudian2020'; //要和上面配置的token令牌一样
        $signature = $_GET['signature'];
        $echostr = $_GET['echostr'];
        $array = array($timestamp, $nonce, $token);
        sort($array);
        $tmpstr = implode('', $array);
        $tmpstr = sha1($tmpstr);
        //如果是第一次访问验证token 否则是接受事件是否关注
        if ($tmpstr == $signature && $echostr) {
            echo $echostr;
            // file_put_contents("code.log", $echostr);
            exit;
        } else {
            //发送消息
            $this->responseMsg();
        }
    }

    /**
     * @user Maxzen
     * @note 消息推送
     */
    public function responseMsg()
    {
        //获取微信推送过来的数据(xml格式)
        $postArr = file_get_contents("php://input");
        //处理消息,并设置回复类型
        $postObj = simplexml_load_string($postArr);
        $mydata = array();
        $mydata['title']=strtolower($postObj->MsgType);
       
        // 消息回复
        if($mydata['title'] == "text"){
            $toUser = $postObj->FromUserName;//用户的openid
            $fromUser = $postObj->ToUserName;
            $time = time();
            $msgType = 'transfer_customer_service';
            $template = "<xml>
                            <ToUserName><![CDATA[".$toUser."]]></ToUserName>
                            <FromUserName><![CDATA[".$fromUser."]]></FromUserName>
                            <CreateTime>".$time."</CreateTime>
                            <MsgType><![CDATA[transfer_customer_service]]></MsgType> 
                        </xml>"; 
            echo $template;
        }
        //关注回复
        if (strtolower($postObj->MsgType) == "event") {
            // 如果是点击事件
            if (strtolower($postObj->Event) == "click"){
            $toUser = $postObj->FromUserName;//用户的openid
            $fromUser = $postObj->ToUserName;
            $time = time();
            $msgType = 'transfer_customer_service';
            $template = "<xml>
                            <ToUserName><![CDATA[".$toUser."]]></ToUserName>
                            <FromUserName><![CDATA[".$fromUser."]]></FromUserName>
                            <CreateTime>".$time."</CreateTime>
                            <MsgType><![CDATA[transfer_customer_service]]></MsgType> 
                        </xml>"; 
            echo $template;
            }
            //如果是关注事件
            if (strtolower($postObj->Event) == "subscribe") {
                //回复用户消息
                $toUser = $postObj->FromUserName;//用户的openid
                $fromUser = $postObj->ToUserName;
                $time = time();
                $msgType = "text";
                $reply = db('weixin_reply')->find(1);
                $content = $reply['reply'];
                
                $jdk = new Jdk_inc();
               
                //获取用户信息
                $userinfo = $jdk->getUserInfo($postObj->FromUserName);
                
                //获取推荐人或者推荐店铺的id
                $father_id = $userinfo['qr_scene_str']?$userinfo['qr_scene_str']:0;
                 
                $nueuser = db("user")->where("openid='{$postObj->FromUserName}'")->find();
               
                try {
                    if (empty($nueuser)) {
                        $wxuser = [
                            'openid' => $userinfo['openid'],
                            'nickname' => $userinfo['nickname'],
                            'avatar' => $userinfo['headimgurl'],
                            'father_id' => (int)$father_id,
                            'subscribe' => 1,
                            'sex' => $userinfo['sex'],
                            "login_num"      =>1, 
                        ];
                        $id = db("user")->insertGetId($wxuser);
                        
                        vipnumber($id);
                        
                        //生成二维码
                        $eqimg = $jdk->getWxCode($id);
                        db('user')->where(['user_id'=>$id])->update(['eqimg'=>$eqimg]);
                        $wxuser['id'] = $id;
                        session("user_id", $id);

                    } else {
                        //生成二维码
                        $eqimg = $jdk->getWxCode($nueuser['user_id']);
                        $wx_user = [
                            'openid' => $userinfo['openid'],
                            'nickname' => $userinfo['nickname'],
                            'avatar' => $userinfo['headimgurl'],
                            'subscribe' => 1, 
                            'eqimg' => $eqimg, 
                        ];
                        
                        $id = $nueuser['user_id'];
                        
                        vipnumber($id);
                        
                        db("user")->where("user_id={$id}")->update($wx_user);
                        db('user')->where("user_id={$id}")->setInc('login_num');

                    }
                    //发送关注回复消息
                    $template = " <xml>
                                  <ToUserName><![CDATA[%s]]></ToUserName>
                                  <FromUserName><![CDATA[%s]]></FromUserName>
                                  <CreateTime>%s</CreateTime>
                                  <MsgType><![CDATA[%s]]></MsgType>
                                  <Content><![CDATA[%s]]></Content>
                                  </xml> ";
                    $info = sprintf($template, $toUser, $fromUser, $time, $msgType, $content);
                    echo $info;
                    // $content2 = "登华山，游关中，就在<a href='https://mp.weixin.qq.com/mp/homepage?__biz=MzUwOTg4NzkzNA%3D%3D&hid=1&sn=d6b24e811979aa25fd7955fdb5e47db1'>【华山旅游资讯网】</a>满足游客“轻松游”“省心游”需求，提供区域旅游一站式服务，聚焦吃\住\行\游\娱\购，有态度的推荐，无边界的服务。登华山而小天下，我们只做价值的传递者和贡献者！";
                    // $kf = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" . $jdk->getToken();
                    // $msgss = [
                    //     'touser' => "$toUser",
                    //     'msgtype' => 'text',
                    //     'text' => ['content' => $content2],
                    // ];
                    // $msg = json_encode($msgss, 256);
                    // $res = httpPost($kf, $msg);
                } catch (\Exception $e) {
                    file_put_contents('error.log', $e->getMessage() . date("Y-m-d H:i:s") . "\n", FILE_APPEND);
                }
                //取消关注
            }elseif (strtolower($postObj->Event) == "unsubscribe") {
                
                $sub_user = db("user")->where("openid='{$postObj->FromUserName}'")->find();
                
                if (!empty($sub_user)) {
                    try {
                        Db::startTrans();
                        db("user")->where("openid='{$postObj->FromUserName}'")->update(['subscribe' => 0]);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                    }
                }
                echo 'ok';
            } 
        }
        
        
        
        
        
      
        // if(strstr($keyword,"客服") ||strstr($keyword,"人工服务"))
        // {
        //     $result = $this->transmitKefu($object);
        //     return $result;
        // }


//         if (strtolower($postObj->MsgType) == "text") {
//             $content2 = trim($postObj->Content);
//             $where[] = "name like '%{$content2}%'";
//             $where[] = "status =0";
//             $word = db("keyword")->where(implode(" and ", $where))->order("id desc")->find();
//             if ($word['type'] == 2) {
//                 $msgType = "news";
//                 $template = "<xml>
//                             <ToUserName><![CDATA[%s]]></ToUserName>
//                             <FromUserName><![CDATA[%s]]></FromUserName>
//                             <CreateTime>%s</CreateTime>
//                             <MsgType><![CDATA[%s]]></MsgType>
//                             <ArticleCount>1</ArticleCount>
//                             <Articles>";
//                 $template .= "<item>
//                                 <Title><![CDATA[" . $word['title'] . "]]></Title>
//                                 <Description><![CDATA[" . $word['desc'] . "]]></Description>
//                                 <PicUrl><![CDATA[" . $word['img'] . "]]></PicUrl>
//                                 <Url><![CDATA[" . $word['url'] . "]]></Url>
//                                 </item>";
//                 $template .= "</Articles></xml>";
//             } else {
//                 $msgType = "text";
//                 $content = $word['content'];
//                 if (empty($word)) {
//                     $content = "登华山，游关中，就在【华山旅游资讯网】
// 满足游客“轻松游”“省心游”需求，提供区域旅游一站式服务，
// 聚焦吃\住\行\游\娱\购，有态度的推荐，无边界的服务。
// 登华山而小天下，我们只做价值的传递者和贡献者！";
//                 }
//                 $template = "<xml>
//                      <ToUserName><![CDATA[%s]]></ToUserName>
//                      <FromUserName><![CDATA[%s]]></FromUserName>
//                      <CreateTime>%s</CreateTime>
//                      <MsgType><![CDATA[%s]]></MsgType>
//                      <Content><![CDATA[" . $content . "]]></Content>
//                      </xml>";
//             }
//             $toUser = $postObj->FromUserName;
//             $fromUser = $postObj->ToUserName;
//             $time = time();
//             echo sprintf($template, $toUser, $fromUser, $time, $msgType);
//         }

    }

private function transmitKefu($object)
    {
    $textTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[transfer_customer_service]]></MsgType>
</xml>";
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }





    /**
     * @user Maxzen
     * @note 微信分享获取js签名
     */
    public function getwx()
    {
        $url = input('url'); 
        $jdk = new Jdk_inc();
        $signPackage = $jdk->getSignPackage($url);
        $appid = db('weixin_config')->where(['wx_id'=>1])->find();
        $data = [
            'debug' => false,
            'appId' => $appid['wx_appid'],
            'timestamp' => $signPackage['timestamp'],
            'nonceStr' => $signPackage['nonceStr'],
            'signature' => $signPackage['signature'], 
        ];
        return json(['code' => 1, 'data' => $data]);
        
    }


    /**
     * @user Maxzen
     * @note 是否微信浏览器
     */

    public function is_weixin()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        }
        return false;
    }

}
